import request from '@/utils/request'

export interface LoginData {
  loginName: string
  password: string
}

export interface LoginRes {
  token: string
  userId: number
  userName: string
  loginName: string
  roles: string[]
}

export interface UserState {
  uid?: number
  nickname?: string
  avatar?: string
  role?: 'applicant' | 'approver' | 'warehouse_manager'
  userId?: number
  userName?: string
  loginName?: string
  roles?: string[]
}

// 角色映射函数
export function mapRoleFromChinese(chineseRoles: string[]): 'applicant' | 'approver' | 'warehouse_manager' {
  const roleMap = {
    '出库申请人': 'applicant',
    '审批人': 'approver', 
    '仓库管理员': 'warehouse_manager'
  }
  
  // 返回第一个匹配的角色，默认为申请人
  for (const chineseRole of chineseRoles) {
    if (roleMap[chineseRole]) {
      return roleMap[chineseRole]
    }
  }
  
  return 'applicant' // 默认角色
}

export function login(data: LoginData): Promise<any> {
  return request.post<LoginRes>('/api/user/login', data)
}

export function logout(token: string): Promise<any> {
  console.log(token)
  return request.post('/api/user/logout', { token })
}

export function getUserInfo() {
  return request<UserState>('/api/user/me')
}

export function getEmailCode(): Promise<any> {
  return request.get('/api/user/email-code')
}

export function resetPassword(): Promise<any> {
  return request.post('/api/user/reset-password')
}

export function register(): Promise<any> {
  return request.post('/api/user/register')
}
